//
//  mm_selectCustomersViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-1.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_selectCustomersViewController.h"
#import "mm_tableViewCellOfCustomerSearch.h"

enum btnTag
{
    xieYiBtn = 100,
    puTongBtn = 200
};

@interface mm_selectCustomersViewController ()

@end

@implementation mm_selectCustomersViewController

@synthesize strStateNumber = _strStateNumber;
@synthesize strIndicationNumber = _strIndicationNumber;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //默认是普通客户
    _customerIdType = MM_CUSTOMER_SEARCH_PU_TONG_KE_HU_KEY_STR_;
    
    //注册消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCustomerList:) name:MM_SEARCH_CUSTOMER_LIST_ object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - button 的回调方法

- (IBAction)backBtnPressed:(UIButton *)sender
{
//    NSLog(@"backBtnPressed !!!");
    
    [self addAllocationListByStatementNumber:self.strStateNumber andIndicationNumber:self.strIndicationNumber];
    
    //跳回上一级页面
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)homeBtnPressed:(UIButton *)sender
{
//    NSLog(@"homeBtnPressed !!!");
    
    //跳回主界面
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)okBtnPressed:(UIButton *)sender
{
//    NSLog(@"okBtnPressed !!!");
    
    [self addAllocationListByStatementNumber:self.strStateNumber andIndicationNumber:self.strIndicationNumber];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)closeBtnPressed:(UIButton *)sender
{
//    NSLog(@"closeBtnPressed !!!");
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidUnload {
    [self setCustomerIdTxt:nil];
    [self setCustomerNameTxt:nil];
    [self setTableViewDis:nil];
    [super viewDidUnload];
}

- (IBAction)xieYiKeHuBtn:(UIButton *)sender
{
    [sender setBackgroundImage:[UIImage imageNamed:@"对号.png"] forState:UIControlStateNormal];
    [(UIButton *)[self.view viewWithTag:puTongBtn] setBackgroundImage:[UIImage imageNamed:@"对号框.png"] forState:UIControlStateNormal];
    _customerIdType = MM_CUSTOMER_SEARCH_XIE_YI_KE_HU_KEY_STR_;
}

- (IBAction)puTongKeHuBtn:(UIButton *)sender
{
    [sender setBackgroundImage:[UIImage imageNamed:@"对号.png"] forState:UIControlStateNormal];
    [(UIButton *)[self.view viewWithTag:xieYiBtn] setBackgroundImage:[UIImage imageNamed:@"对号框.png"] forState:UIControlStateNormal];
    _customerIdType = MM_CUSTOMER_SEARCH_PU_TONG_KE_HU_KEY_STR_;
}

- (IBAction)searchBtn:(UIButton *)sender
{
//    [self jsonParseFromMultipleCustomerAllocation];
    
    //请求数据，发送消息
    webService *web=[[webService alloc] init];
    web.methodName = MM_SEARCH_CUSTOMER_LIST_;
    
    NSMutableArray *arrTmp = [NSMutableArray array];
    [arrTmp addObject:@"customerType"];
    [arrTmp addObject:[NSString stringWithFormat:@"%i",_customerIdType]];
    
    if (!(
          self.customerIdTxt.text == nil
          ||
          [self.customerIdTxt.text isEqualToString:@""]
        ))
    {
        [arrTmp addObject:@"customerId"];
        [arrTmp addObject:_customerIdTxt.text];
    }
    
    if (!(
          self.customerNameTxt.text == nil
          ||
          [self.customerNameTxt.text isEqualToString:@""]
        ))
    {
        [arrTmp addObject:@"customerName"];
        [arrTmp addObject:_customerNameTxt.text];
    }
    
    [web commonGetSharedRequest:web.methodName wsparas:arrTmp];
    
    [SVProgressHUD showWithStatus:@"请等待...."];
}

#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5 + [_arrAllTheCustomers count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *cellIdentifier = @"cell";
    mm_tableViewCellOfCustomerSearch *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell)
    {
        cell = [[mm_tableViewCellOfCustomerSearch alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    NSInteger row = [indexPath row];
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            break;
            
        default:
            break;
    }
    
    //显示数据
    if (row<[_arrAllTheCustomers count])
    {
        for (int i = 0; i<[cell.arrForKeys count]; i++)
        {
            NSString *strKey = [cell.arrForKeys objectAtIndex:i];
            if ([strKey isEqualToString:MM_CUSTOMER_SEARCH_MARK_KEY_STR_])
            {
                if ([[[_arrForTheSelState objectAtIndex:row] objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_] isEqualToString:@"1"])
                {
                    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"对号.png"]];
                    [((UILabel *)[cell.dicForLblsOnCell objectForKey:strKey]) addSubview:imgView];
                }
                continue;
            }
            ((UILabel *)[cell.dicForLblsOnCell objectForKey:strKey]).text = [[_arrAllTheCustomers objectAtIndex:row] objectForKey:strKey];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        for (int i = 0; i<[cell.arrForKeys count]; i++)
        {
            NSString *strKey = [cell.arrForKeys objectAtIndex:i];
            if ([strKey isEqualToString:MM_CUSTOMER_SEARCH_MARK_KEY_STR_])
            {
                NSArray *subViews = [((UILabel *)[cell.dicForLblsOnCell objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_]) subviews];
                for (id obj in subViews)
                {
                    [obj removeFromSuperview];
                }
                continue;
            }
            
            ((UILabel *)[cell.dicForLblsOnCell objectForKey:strKey]).text = @"";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

#pragma mark - tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    if (row<[_arrAllTheCustomers count])
    {
        //响应点击
        mm_tableViewCellOfCustomerSearch *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *strTmp = [[_arrForTheSelState objectAtIndex:row] objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_];
        if ([strTmp isEqualToString:@""])
        {
            NSDictionary *dicTmp = [NSDictionary dictionaryWithObject:@"1" forKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_];
            [_arrForTheSelState setObject:dicTmp atIndexedSubscript:row];
        }
        else
        {
            NSDictionary *dicTmp = [NSDictionary dictionaryWithObject:@"" forKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_];
            [_arrForTheSelState setObject:dicTmp atIndexedSubscript:row];
        }
        if ([[[_arrForTheSelState objectAtIndex:row] objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_] isEqualToString:@"1"])
        {
            UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"对号.png"]];
            [((UILabel *)[cell.dicForLblsOnCell objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_]) addSubview:imgView];
        }
        else
        {
            NSArray *subViews = [((UILabel *)[cell.dicForLblsOnCell objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_]) subviews];
            for (id obj in subViews)
            {
                [obj removeFromSuperview];
            }
        }
    }
    else
    {
        return;
    }
}

/*just for test*/
-(void)jsonParseFromMultipleCustomerAllocation
{
    NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"JsonFileForMultipleCustomerAllocation" ofType:@"json"];
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[HelpClass jsonParseByJsonFileStr:jsonFilePath]];
    
//    NSLog(@"dic = %@",dic);
    
    _arrAllTheCustomers = [dic objectForKey:MM_CUSTOMER_LIST_KEY_STR_];
}
/*end of just for test*/

//根据陈述号和指示号确定多客户分配的选择项，然后将选择的客户加入到该选择项中
-(void)addAllocationListByStatementNumber:(NSString *)statementNumber andIndicationNumber:(NSString *)indicationNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arrAllocationListTmp = modelIns.arrAllocationList;
    
    for (int i = 0; i<[arrAllocationListTmp count]; i++)
    {
        NSString *strStateNumberTmp = [[arrAllocationListTmp objectAtIndex:i] objectForKey:MM_ALLOCATION_STATEMENT_NUMBER_KEY_STR_];
        NSString *strIndicationNumberTmp = [[arrAllocationListTmp objectAtIndex:i] objectForKey:MM_ALLOCATION_INDICATION_NUMBER_KEY_STR_];
        
        if ([statementNumber isEqualToString:strStateNumberTmp]
            &&
            [indicationNumber isEqualToString:strIndicationNumberTmp])
        {
            NSMutableArray *arrCustomerListTmp = [NSMutableArray arrayWithArray:[[arrAllocationListTmp objectAtIndex:i] objectForKey:MM_CUSTOMER_LIST_KEY_STR_]];
            
            for (int j = 0; j<[_arrForTheSelState count]; j++)
            {
                if ([[[_arrForTheSelState objectAtIndex:j] objectForKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_] isEqualToString:@"1"])
                {
                    /*
                     "customerList": [
                     {
                     "customerId": "201003030008",
                     "customerName": "翁小姐",
                     "proportion": "100.00",
                     "money": "0",
                     "balanceFlag": "0"
                     }
                     ]
                     */
                    
                    //此行对应的客户被选中
                    NSMutableDictionary *dicSel = [NSMutableDictionary dictionaryWithDictionary:[_arrAllTheCustomers objectAtIndex:j]];
                    [dicSel setObject:@"0.00" forKey:MM_CUSTOMER_REPAIR_MONEY_KEY_STR_];
                    
                    NSDictionary *dicCustomerTmp = [NSDictionary dictionaryWithObjectsAndKeys:
                                                    [dicSel objectForKey:MM_CUSTOMER_NUMBER_KEY_STR_],MM_CUSTOMER_NUMBER_KEY_STR_,
                                                    [dicSel objectForKey:MM_CUSTOMER_NAME_KEY_STR_],MM_CUSTOMER_NAME_KEY_STR_,
                                                    @"0",MM_CUSTOMER_PROPORTION_KEY_STR_,
                                                    @"0.00",MM_CUSTOMER_REPAIR_MONEY_KEY_STR_,
                                                    [NSString stringWithFormat:@"%i",MM_BALANCE_OWNER],MM_CUSTOMER_BALANCE_FLAG_KEY_STR_, nil];
                    //将选中的客户加入客户数组中
                    [arrCustomerListTmp addObject:dicCustomerTmp];
                }
            }
                        
            //将新的客户列表加入客户分配列表中
            NSMutableDictionary *dicAllocationListTmp = [NSMutableDictionary dictionaryWithDictionary:[arrAllocationListTmp objectAtIndex:i]];
//            NSLog(@"%@",dicAllocationListTmp);
            [dicAllocationListTmp setObject:arrCustomerListTmp forKey:MM_CUSTOMER_LIST_KEY_STR_];
//            NSLog(@"%@",dicAllocationListTmp);
            
            NSMutableArray *arrFinalFinalAllocaitonList = [NSMutableArray arrayWithArray:arrAllocationListTmp];
            [arrFinalFinalAllocaitonList setObject:dicAllocationListTmp atIndexedSubscript:i];
            
            modelIns.arrAllocationList = [NSMutableArray arrayWithArray:arrFinalFinalAllocaitonList];
            
//            NSLog(@"%@",modelIns.arrAllocationList);
            
            return;
        }
    }
}

//获取客户列表回调方法
-(void)getCustomerList:(NSNotification*)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    
    _arrAllTheCustomers = [theJson objectForKey:@"customerList"];
    
    _arrForTheSelState = [NSMutableArray arrayWithCapacity:[_arrAllTheCustomers count]];
    
    //初始化选择的状态
    for (int i = 0; i<[_arrAllTheCustomers count]; i++)
    {
        NSDictionary *dicTmp = [NSDictionary dictionaryWithObject:@"" forKey:MM_CUSTOMER_SEARCH_MARK_KEY_STR_];
        [_arrForTheSelState addObject:dicTmp];
    }
//    NSLog(@"%@",_arrForTheSelState);
    
    [self.tableViewDis reloadData];
    
    [SVProgressHUD dismiss];
}

@end
